import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import 'rxjs/add/operator/toPromise';

import { Course } from '../components/Interfaces/Course';

const httpOptions = {
  headers: new Headers({
    'Content-Type': 'application/json',
  })
};

@Injectable()
export class CourseService {

    private apiUrl = '/api/v1/courses';  // URL to web api

    constructor(
        private http: Http,
    ) { }

    /**
     * 列表
     */
    getCourses(): Observable<any> {
        return this.http.get(this.apiUrl, httpOptions).map(res => res.json());
    }

    /**
     * 新增课程
     */
    addCourse(course: Course): Observable<any> {
        return this.http.post(this.apiUrl, course, httpOptions).map(res => res.json());
    }

    /**
     * 编辑课程
     * @param course
     */
    editCourse(course: Course): Observable<any> {
        return this.http.put(this.apiUrl + '/' + course.id, course, httpOptions).map(res => res.json());
    }

    deleteCourse(course: Course): Observable<any> {
        return this.http.delete(this.apiUrl + '/' + course.id, httpOptions)
                .map(res => res.json());
    }
}
